﻿
using RuoVea.Entity;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.Threading.Tasks;
using RuoVea.ExSqlSugar;
using RuoVea.ExDto;
using RuoVea.ExEnum;
using Microsoft.Extensions.DependencyInjection;
using RuoVea.Autowired;
using RuoVea.ExUtil.Exceptions;
using RuoVea.ExUtil.EnumExtension;

namespace RuoVea.Service
{
    /// <summary>
    /// 用户管理
    /// </summary>
    [AppService(ServiceLifetime.Scoped)]
    public class UserManager : IUserManager
    {
        private readonly ISqlSugarRepository<SysUser> _sysUserRep; // 用户表仓储   
        private readonly IHttpContextAccessor _httpContextAccessor;

        public long UserId
        {
            get => long.Parse(_httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
        }

        public string Account
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
        }

        public string Name
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value;
        }

        public bool SuperAdmin
        {
            get => _httpContextAccessor.HttpContext.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == ((int)AdminType.SuperAdmin).ToString();
        }

        public SysUser User
        {
            get => _sysUserRep.FirstOrDefault(u => u.Id == UserId);
        }

        public UserManager(ISqlSugarRepository<SysUser> sysUserRep,IHttpContextAccessor httpContextAccessor)
        {
            _sysUserRep = sysUserRep;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="tracking"></param>
        /// <returns></returns>
        public async Task<SysUser> CheckUserAsync(long userId, bool tracking = true)
        {
            var user = await _sysUserRep.FirstOrDefaultAsync(u => u.Id == userId);
            return user ?? throw new ParamiterException(ErrorCode.D1002.GetEnumText());
        }
    }
}